package com.obggtc.picture.utils;
import org.bytedeco.javacv.*;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;

public class VideoUtils {

    /**
     * 提取视频缩略图
     * @param videoPath  视频文件路径
     * @param second     截取的时间点（单位：秒）
     * @param outputPath 输出图片路径
     * @throws Exception
     */
    public static void extractThumbnail(String videoPath, int second, String outputPath) throws Exception {
        FFmpegFrameGrabber grabber = new FFmpegFrameGrabber(videoPath);
        grabber.start();

        long targetTime = second * 1_000_000L; // 微秒
        grabber.setTimestamp(targetTime);

        Frame frame = grabber.grabImage();
        if (frame != null) {
            Java2DFrameConverter converter = new Java2DFrameConverter();
            BufferedImage bi = converter.convert(frame);
            ImageIO.write(bi, "jpg", new File(outputPath));
        }

        grabber.stop();
    }

    /**
     * 生成视频缩略图
     * @param videoFile       输入视频文件
     * @param outputImageFile 输出图片文件
     * @return true = 成功生成缩略图
     */
    public static boolean generateSmartThumbnail(File videoFile, File outputImageFile) {
        FFmpegFrameGrabber grabber = null;
        try {
            grabber = new FFmpegFrameGrabber(videoFile);
            grabber.start();

            // 视频时长（微秒）
            long duration = grabber.getLengthInTime();
            if (duration <= 0) {
                return false;
            }

            // 取视频中间 20% 处的帧，避免片头/片尾是黑屏
            long targetTime = duration / 5;
            grabber.setTimestamp(targetTime);

            Frame frame = grabber.grabImage();
            if (frame == null) {
                return false;
            }

            // 转 BufferedImage
            Java2DFrameConverter converter = new Java2DFrameConverter();
            BufferedImage bi = converter.convert(frame);

            // 输出到文件（jpg/png）
            String format = getFileExtension(outputImageFile);
            if (format == null) {
                format = "jpg"; // 默认 jpg
            }
            ImageIO.write(bi, format, outputImageFile);

            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            try {
                if (grabber != null) grabber.stop();
            } catch (Exception ignore) {}
        }
    }

    /** 获取文件扩展名 */
    public static String getFileExtension(File file) {
        String name = file.getName();
        int dotIndex = name.lastIndexOf('.');
        if (dotIndex > 0 && dotIndex < name.length() - 1) {
            return name.substring(dotIndex + 1).toLowerCase();
        }
        return null;
    }



    public static void main(String[] args) throws Exception {
        extractThumbnail("input.mp4", 5, "thumb.jpg");
        System.out.println("缩略图已生成");

        VideoUtils generator = new VideoUtils();
        boolean ok = generator.generateSmartThumbnail(
                new File("input.mp4"),
                new File("thumb.jpg")
        );
        System.out.println("生成结果: " + ok);
    }
}
